package com.wondersgroup.fjzlpt.plat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.auth.login.LoginService;
import com.wondersgroup.fjzlpt.plat.dao.impl.LoginDAOImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Map;

/**
 * Created by lion on 2017/5/21.
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginDAOImpl loginDAO;

    /**
     * 查询用户唯一ID
     * @param username
     * @param password
     * @return
     */
    @Override
    public String queryUserUniqueId(String username, String password) {
        return this.loginDAO.queryUserUniqueId(username, password);
    }

    /**
     * 查询用户信息
     * @param map
     * @return
     */
    public JSONObject queryUserInfo(Map map){
        String USERID = (String)map.get("USERID");
        return this.loginDAO.queryUserInfo(USERID);
    }

    /**
     * 查询用户角色信息
     * @param map
     * @return
     */
    public JSONObject queryUserRoleInfo(Map map){
        String USERID = (String)map.get("USERID");
        /*获取角色信息*/
        JSONObject roleInfo = this.loginDAO.queryUserRoleInfo(USERID);
        JSONArray menus = roleInfo.getJSONArray("MENUS");
        /*获取角色可使用的url*/
        JSONArray URLS = getRoleMatchUrlAry(menus);
        roleInfo.put("URLS", URLS);
        /*获取导航菜单*/
        JSONArray newMenus = getMenuAry(menus);
        roleInfo.put("MENUS", newMenus);
        return roleInfo;
    }

    /**
     * 获取导航
     * @param ary
     * @return
     */
    private JSONArray getMenuAry(JSONArray ary){
        JSONArray menuAry = new JSONArray(ary);
        Iterator iter = menuAry.iterator();
        while(iter.hasNext()) {
            JSONObject menu = (JSONObject) iter.next();
            /*删除非导航的节点*/
            if(!"1".equals(menu.getString("NAVIGATE"))){
                iter.remove();
            }
        }
        return menuAry;
    }

    /**
     * 获取可用 URL
     * @param ary
     * @return
     */
    private JSONArray getRoleMatchUrlAry(JSONArray ary){
        JSONArray urls = new JSONArray();
        Iterator iter = ary.iterator();
        while(iter.hasNext()){
            JSONObject menu = (JSONObject)iter.next();
            String url = menu.getString("VIEWURL");
            if(!StringUtils.isEmpty(url)){
                urls.add(url);
            }
        }
        return urls;
    }

    @Override
    public String queryUserUniqueId(Map map) {
        return null;
    }
}
